package hotactivity

import (
	"advertoper/db"

	"doubimeizhi.com/datatable"

	log "github.com/cihub/seelog"
)

var (
	hotActivity map[int64]*HotActivityInfo

	activityCatalog map[int][]int64
)

func getActivityCatalogSize(status int) int {
	if activityCatalog == nil {
		return 0
	}
	if aids, ok := activityCatalog[status]; ok {
		return len(aids)
	}
	return 0
}

func init() {
	hotActivity = make(map[int64]*HotActivityInfo)

	activityCatalog = make(map[int][]int64)

	loadFromDB()

	go periodupMemory()
}

func loadFromDB() {
	dtq := datatable.NewDataTableQuery()
	dtq.SetTableName("hot_activity")
	dtq.PushField(&datatable.FiledItem{Alias: "activity_id", Field: "activity_id", OrderBy: datatable.DESC})
	dtq.PushField(&datatable.FiledItem{Alias: "thumbnail_url", Field: "thumbnail_url"})
	dtq.PushField(&datatable.FiledItem{Alias: "target_url", Field: "target_url"})
	dtq.PushField(&datatable.FiledItem{Alias: "publish_tick", Field: "publish_tick"})
	dtq.PushField(&datatable.FiledItem{Alias: "end_tick", Field: "end_tick"})
	dtq.PushField(&datatable.FiledItem{Alias: "pic_size", Field: "pic_size"})
	dtq.PushField(&datatable.FiledItem{Alias: "title", Field: "title"})

	sql, values := dtq.GenerateSQL()
	mysqlHelper := db.GetMysqlHelper()
	results, err := mysqlHelper.Query(sql, values...)
	if err != nil {
		log.Warnf("sql err: %s, sql: %s, values: %v", err.Error(), sql, values)
		return
	}

	for _, dt := range results {
		hot := &HotActivityInfo{}
		hot.ActivityId = mysqlHelper.GetColInt64(dt, "activity_id")
		hot.ThumbnailURL = mysqlHelper.GetColString(dt, "thumbnail_url")
		hot.Size = mysqlHelper.GetColString(dt, "pic_size")
		hot.TargetURL = mysqlHelper.GetColString(dt, "target_url")
		hot.PublishTick = mysqlHelper.GetColInt64(dt, "publish_tick")
		hot.EndTick = mysqlHelper.GetColInt64(dt, "end_tick")
		hot.Title = mysqlHelper.GetColString(dt, "title")
		status := hot.GetStatus()
		hot.Status = status

		hotActivity[hot.ActivityId] = hot
		if _, ok := activityCatalog[status]; ok {
			activityCatalog[status] = append(activityCatalog[status], hot.ActivityId)
		} else {
			activityCatalog[status] = make([]int64, 0)
			activityCatalog[status] = append(activityCatalog[status], hot.ActivityId)
		}
	}
}
